package com.founder.gateway.system.util;

import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.founder.gateway.component.transport.netty.http.NettyHttpRequest;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;

/**
 * 统一Http返回信息
 */
public class HttpNormUtil {
    // 以此开头的 http-header 作为内部信息 不传递
    public static final String HEADER_FOUNDER = "founder.";
    // 错误提示信息
    public static final String NOT_BLANK = " 不能为空！";
    public static final String NOT_FOUND = " 未找到接口！";
    public static final String DATA_MATCH_ERROR = " Data 字段匹配错误";
    // content-type 追加 字符集
    public static final String APPEND_UTF_8 = "; charset=utf-8";

    public static String getLastPart(String uri) {
        int i = uri.indexOf('?');
        if (i != -1) {
            uri = uri.substring(0, i);
        }
        i = uri.length() - 1;
        if (uri.endsWith("/")) {
            i--;
        }
        return uri.substring(uri.lastIndexOf("/", i) + 1, i + 1);
    }

    public static boolean isAnyBlank(List<String> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        for (String item : list) {
            if (StringUtils.isBlank(item)) {
                return true;
            }
        }
        return false;
    }

    private static Pattern GET_REST_PARAMS_PATTERN = Pattern.compile("\\{.*?}");

    public static Set<String> getRestParams(String url) {
        Set<String> params = new HashSet<>();
        Matcher matcher = GET_REST_PARAMS_PATTERN.matcher(url);
        while (matcher.find()) {
            params.add(matcher.group());
        }
        return params;
    }

    public static boolean isAllBlank(List<String> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        for (String item : list) {
            if (StringUtils.isNotBlank(item)) {
                return false;
            }
        }
        return true;
    }

    public static String getRemoteIp(NettyHttpRequest request, ChannelHandlerContext ctx) {
        String ip = request.headers().get("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.headers().get("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        try {
            return ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
        } catch (Exception e) {
            return null;
        }
    }
}
